package com.fenquen.dfs.router.multicast;

import com.fenquen.dfs.router.protocol.ProtocolOperator;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;

@Component
public class MulticastServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private static final Logger LOGGER = LoggerFactory.getLogger(MulticastServerHandler.class);

    @Autowired
    private ProtocolOperator protocolOperator;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {
        protocolOperator.getData(ByteBuffer.wrap(ByteBufUtil.getBytes(datagramPacket.content())));

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        cause.printStackTrace();
        // We don't close the channel because we can keep serving requests.
    }
}
